from flask import Flask, request, session, render_template, redirect
import pymysql

app = Flask(__name__, template_folder='templates',
            static_folder='static', static_url_path='')
app.secret_key = "skhfiau2kjbkkd"
dict = {'mutex':0}

def get_mysql(usr, pwd):
    db = pymysql.connect(user='root', password='123456', host='127.0.0.1', database='test')
    curor = db.cursor()
    curor.execute("select passwd from admin where username='{}'".format(usr))
    data = curor.fetchone()
    if data == None:
        return False
    db.close()
    if data[0] == pwd:
        return True
    else:
        return False

@app.route('/', methods=["GET", "POST"])
def hello_world():
    return redirect('/login')

# 登录界面
@app.route('/login', methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return render_template("login.html")
    if request.method == "POST":
        session['usr'] = request.form.get("usr")
        session['passwd'] = request.form.get('passwd')

        if session['usr'] and session['passwd']:
            if get_mysql(session['usr'], session['passwd']):
                dict['mutex'] = 1
                return redirect('/index')
            else:
                return render_template("login.html", msg="Yours username or password is wrong")
        else:
            return render_template("login.html", msg="Yours username or password is none")



# 欢迎界面
@app.route('/index')
def index():
    if dict['mutex'] == 0:
        return redirect('/login')
    elif dict['mutex'] == 1 and request.method == "GET":
        dict['mutex'] = 0
        return render_template('index.html')
    # if request.method == "POST":
    #     session['table_id'] = request.form.get("table_id")
    #     session['question'] = request.form.get("question")
    #     db = pymysql.connect(user='root', password='123456', host='127.0.0.1')


    # if request.method == "POST":
    #


def let_enrollment(usr, passwd1, passwd2):
    db = pymysql.connect(user='root', password='123456', host='127.0.0.1', database='test')
    curor = db.cursor()
    curor.execute("select username from admin")
    data = curor.fetchall()
    for line in list(data):
        if usr == line[0]:
            print("用户名存在")
            return "用户名存在, 请重新注册"
        else:
            print("用户可以注册")
    if passwd1 == passwd2:
        curor.execute("insert into admin values('{}', '{}')".format(usr, passwd1))
        db.commit()
        db.close()
    return "用户可以注册"


# 注册界面
@app.route('/enrollment', methods=["GET", "POST"])
def enrollment():
    if request.method == "GET":
        return render_template('enrollment.html')
    if request.method == "POST":
        session['re_usr'] = request.form.get("usr")
        session['re_passwd'] = request.form.get('passwd')
        print("1", session['re_passwd'])
        session['re_passwd2'] = request.form.get('passwd2')
        print("2", session['re_passwd2'])
        print(session['re_usr'], session['re_passwd'])
        if session['re_usr'] and session['re_passwd'] and session['re_passwd2']:
            msg = let_enrollment(session['re_usr'], session['re_passwd'], session['re_passwd2'])
            return render_template('login.html', msg=msg)
        else:
            return render_template('enrollment.html')


if __name__ == "__main__":
    app.run(host="127.0.0.1", port=5000, debug=True)